package com.wg.msuser.config;

import org.springframework.stereotype.Component;

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

@Component
public class SimpleEmailSender {

    // QQ邮箱SMTP服务器配置
    private static final String SMTP_HOST = "smtp.qq.com";
    private static final int SMTP_PORT = 587;
    private static final String USERNAME = "3162136641@qq.com";
    private static final String PASSWORD = "zztmuptaniyrdcfe";

    public static void sendTextEmail(String to, String subject, String content) {
        // 1. 配置邮件服务器属性
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", SMTP_HOST);
        props.put("mail.smtp.port", SMTP_PORT);

        // 2. 创建Session对象
        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(USERNAME, PASSWORD);
            }
        });

        try {
            // 3. 创建邮件消息
            Message message = new MimeMessage(session);
            // 发件人
            message.setFrom(new InternetAddress(USERNAME));
            // 收件人
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            // 主题
            message.setSubject(subject);
            // 内容
            message.setText(content);

            // 4. 发送邮件
            Transport.send(message);
            System.out.println("邮件发送成功");
        } catch (MessagingException e) {
            System.err.println("邮件发送失败: " + e.getMessage());
            throw new RuntimeException("邮件发送失败", e);
        }
    }

    public static void main(String[] args) {
        sendTextEmail("2836338256@qq.com", "测试邮件", "这是一封测试邮件内容");
    }
}